package com.lzb.watermarkcamera.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzb.watermarkcamera.AppConfig;
import com.lzb.watermarkcamera.BaseAc;
import com.lzb.watermarkcamera.Content;
import com.lzb.watermarkcamera.R;
import com.lzb.watermarkcamera.adapter.PictureReportAdapter;
import com.lzb.watermarkcamera.basic.utils.FileUtil;
import com.lzb.watermarkcamera.basic.utils.IntentUtil;
import com.lzb.watermarkcamera.basic.utils.RxUtil;
import com.lzb.watermarkcamera.databinding.ActivityPictureReportBinding;
import com.lzb.watermarkcamera.databinding.ActivitySelPictureBinding;
import com.lzb.watermarkcamera.dialog.SelDateScopeDialog;
import com.lzb.watermarkcamera.dialog.SelTimeDialog;
import com.lzb.watermarkcamera.utils.ViewToBitmapUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

public class PictureReportActivity extends BaseAc<ActivityPictureReportBinding> implements View.OnClickListener {

    private PictureReportAdapter reportAdapter;
    private List<String> listAll = new ArrayList<>();
    private long startDate, endDate;
    private SelDateScopeDialog selDateScopeDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_picture_report;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPictureReportBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvDate.setOnClickListener(this);
        mDataBinding.tvShare.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);

        mDataBinding.rvPictureList.setLayoutManager(new LinearLayoutManager(mContext));
        reportAdapter = new PictureReportAdapter();
        mDataBinding.rvPictureList.setAdapter(reportAdapter);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvDate) {//日期
            showSelTimeDialog();
        } else if (id == R.id.tvShare) {//分享
            Bitmap bitmap = ViewToBitmapUtils.convertWideView(mDataBinding.scSave);
            String filePath = FileUtil.generateFilePath(Content.Temp, ".png");
            ImageUtils.save(bitmap, filePath, Bitmap.CompressFormat.PNG);
            IntentUtil.shareFile(mContext,filePath);
        } else if (id == R.id.tvSave) {//保存
            saveImg();
        }
    }

    @Override
    protected void initData() {
        String date = TimeUtils.getNowString(new SimpleDateFormat("yyyy.MM.dd"));
        startDate = TimeUtils.string2Millis(date, new SimpleDateFormat("yyyy.MM.dd"));
        endDate = TimeUtils.string2Millis(date, new SimpleDateFormat("yyyy.MM.dd"));
        mDataBinding.tvDate.setText(date + "-" + date);
        getData();
    }

    private void getData() {
        String path = PathUtils.getFilesPathExternalFirst() + Content.myCamera;
        List<File> files = FileUtils.listFilesInDir(path);
        listAll.clear();
        if (files.size() > 0) {
            for (File file : files) {
                listAll.add(file.getPath());
            }
        }
        filter();
    }

    private void filter() {
        List<String> listShow = new ArrayList<>();

        // 遍历listAll，筛选出在startDate和endDate时间范围内的文件
        for (String filePath : listAll) {
            File file = new File(filePath);
            if (file.exists()) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                long fileModifiedTime = TimeUtils.string2Millis(TimeUtils.millis2String(FileUtils.getFileLastModified(file), format), format);
                // 检查文件修改时间是否在指定时间范围内
                if (fileModifiedTime >= startDate && fileModifiedTime <= endDate) {
                    listShow.add(filePath);
                }
            }
        }

        reportAdapter.setList(listShow);
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.save_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        Bitmap bitmap = ViewToBitmapUtils.convertWideView(mDataBinding.scSave);
                        //保存到相册
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        finish();
                    }
                });
            }
        }, 1000);
    }

    private void showSelTimeDialog() {
        if (selDateScopeDialog == null) selDateScopeDialog = new SelDateScopeDialog(mContext);
        selDateScopeDialog.setListener(new SelDateScopeDialog.Ilistener() {
            @Override
            public void clickConfirm(long start, long end) {
                startDate = start;
                endDate = end;
                mDataBinding.tvDate.setText(TimeUtils.millis2String(startDate, new SimpleDateFormat("yyyy.MM.dd")) + "-" + TimeUtils.millis2String(endDate, new SimpleDateFormat("yyyy.MM.dd")));
                filter();
            }
        });
        selDateScopeDialog.show();
    }
}